#!/bin/bash
if [ $# -lt 1 ];then
  echo "Usage: $0 [txtWordlist]"
  exit 1
fi

wordlst=$1
eachIndex=0
POSTFIX_URL="--_us_1.mp3"
TEMPLATE_URL="https://ssl.gstatic.com/dictionary/static/sounds/oxford/"
POSTFIX_YOUDAO="&le=eng"
TEMPLATE_YOUDAO="http://dict.youdao.com/dictvoice?audio="

#while read iw
echo -e "wordlist==>mp4:"
if [[ -d ${wordlst%.*} ]]; then
  rm -rf ${wordlst%.*}
fi

mkdir ${wordlst%.*}
gsed -i "s/ /+/g" ${wordlst}
for iw in $(cat ${wordlst})
do
  echo "${iw}"
  if [[ ${iw} =~ "+" ]];then
    MP3URL="${TEMPLATE_YOUDAO}${iw}${POSTFIX_YOUDAO}"
  else
    MP3URL="${TEMPLATE_URL}${iw}${POSTFIX_URL}"
  fi

  let eachIndex=eachIndex+1
  if [ ! -f "curlwords/${iw}.mp3" ];then
    curl --connect-timeout 10 -m 20 "${MP3URL}" --output "curlwords/${iw}.mp3"
    sleep 1 #sleep for crawler
  fi

  ffmpeg -hide_banner -vn -f lavfi -i anullsrc=channel_layout=stereo:sample_rate=44100 -i "curlwords/${iw}.mp3" -filter_complex amix=inputs=2:duration=longest -t 6 -acodec aac -ar 32000 -ac 2 -y -f mp4 "${wordlst%.*}/w${eachIndex}.mp4" 2>/dev/null 1>/dev/null
done

cat /dev/null > mp4merge.list
for ((each=1;each<=${eachIndex};each++))
do
  if [ -f ${wordlst%.*}/w${each}.mp4 ];then
    echo "file ${wordlst%.*}/w${each}.mp4"
  fi
done>>mp4merge.list
ffmpeg -hide_banner -f concat -safe 0 -i mp4merge.list -c copy -y "${wordlst%.*}_list.mp4"
exit 0

